package com.un.ebs.purchase.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.un.ebs.contract.domain.ContractItemExt;
import com.un.ebs.contract.dto.ContractVo;
import com.un.ebs.contract.enums.ContractTypeEnum;
import com.un.ebs.contract.service.ContractService;
import com.un.ebs.core.exception.BusinessEntityNotFoundException;
import com.un.ebs.core.exception.BusinessException;
import com.un.ebs.core.util.DateUtils;
import com.un.ebs.core.util.SecurityUtils;
import com.un.ebs.core.util.StringUtils;
import com.un.ebs.inventory.domain.InventoryNoteItemExt;
import com.un.ebs.inventory.domain.InventoryNoteType;
import com.un.ebs.inventory.enums.InventoryTypeEnum;
import com.un.ebs.inventory.service.InventoryNoteService;
import com.un.ebs.product.domain.ProductSkuExt;
import com.un.ebs.product.service.ProductSkuService;
import com.un.ebs.production.domain.ProductionOrderView;
import com.un.ebs.production.domain.ProductionRequirementPlanExt;
import com.un.ebs.production.domain.ProductionSeqItem;
import com.un.ebs.production.mapper.ProductionRequirementPlanExtMapper;
import com.un.ebs.production.mapper.ProductionSeqItemMapper;
import com.un.ebs.production.service.ProductionOrderService;
import com.un.ebs.purchase.domain.*;
import com.un.ebs.purchase.dto.*;
import com.un.ebs.purchase.enums.PurchaseOrderTypeEnum;
import com.un.ebs.purchase.mapper.*;
import com.un.ebs.purchase.service.PurchaseOrderService;
import com.un.ebs.sys.domain.Ent;
import com.un.ebs.sys.domain.Personnel;
import com.un.ebs.sys.service.EntService;
import com.un.ebs.sys.service.PersonnelService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.logging.Logger;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author liubo
 * @since 2020-05-30
 */
@Service
public class PurchaseOrderServiceImpl extends ServiceImpl<PurchaseOrderMapper, PurchaseOrder> implements PurchaseOrderService {

    @Resource
    private PurchaseOrderExtMapper purchaseOrderExtMapper;

    @Resource
    private PurchaseOrderItemMapper purchaseOrderItemMapper;

    @Resource
    private PurchaseOrderItemExtMapper purchaseOrderItemExtMapper;

    @Resource
    private PurchaseInNoteToFinanceMapper purchaseInNoteToFinanceMapper;

    @Resource
    private ProductionSeqItemMapper productionSeqItemMapper;

    @Resource
    private PurchaseInNoteExtMapper purchaseInNoteExtMapper;

    @Resource
    private PurchaseOrderDeliverPlanExt purchaseOrderDeliverPlanExt;

    @Resource
    private ProductSkuService productSkuService;

    @Resource
    private ContractService contractService;

    @Resource
    private ProductionOrderService productionOrderService;

    @Resource
    private InventoryNoteService inventoryNoteService;

    @Resource
    private PurchaseSummaryItemExtMapper purchaseSummaryItemExtMapper;

    @Resource
    private ProductionRequirementPlanExtMapper productionRequirementPlanExtMapper;

    @Resource
    private PurchaseMonthSumExtMapper purchaseMonthSumExtMapper;

    @Resource
    private PurchaseSummaryExtMapper purchaseSummaryExtMapper;

    @Resource
    private EntService entService;

    @Resource
    private PersonnelService personnelService;

    private final Logger logger = Logger.getLogger(PurchaseOrderServiceImpl.class.getName());

    @Transactional
    @Override
    public String add(PurchaseOrderAddDto req) {
        PurchaseOrderUpdateDto obj = new PurchaseOrderUpdateDto();
        BeanUtils.copyProperties(req, obj);
        return save(obj);
    }

    @Override
    public String add(PurchaseOrderAddBySimpleDto req) {
        LambdaQueryWrapper<ProductionRequirementPlanExt> lq = Wrappers.lambdaQuery();
        lq.eq(ProductionRequirementPlanExt::getSkuId, req.getSkuId());
        ProductionRequirementPlanExt requirementPlanExt = productionRequirementPlanExtMapper.selectOne(lq);

        if (requirementPlanExt == null) {
            throw new BusinessException("没有找到相应的采购需求。");
        }
        if (requirementPlanExt.getPurchaseRequirementQty() < req.getQty()) {
            ProductSkuExt sku = productSkuService.queryViewById(req.getSkuId());
            if (sku == null) {
                throw new BusinessEntityNotFoundException(req.getSkuId(), "SKU");
            }
//            if (req.getQty() > sku.getBuyMinQty()) {
//                throw new BusinessException(String.format("当前采购数量 %s 不能大于采购需求数量 %s ，同时不能大于最小采购量 %s", req.getQty(), requirementPlanExt.getPurchaseRequirementQty(), sku.getBuyMinQty()));
//            }
            throw new BusinessException(String.format("当前采购数量 %s 不能大于采购需求 %s。", req.getQty(), requirementPlanExt.getPurchaseRequirementQty()));
        }

        Optional<ContractItemExt> contractItemExt = contractService.queryItemBySku(req.getSkuId(), 999, 1).getRecords().stream().filter(s -> requirementPlanExt.getProviderEntId().equals(s.getBusinessEntId()) && s.getAuditStatus() == true).findFirst();
        if (!contractItemExt.isPresent()) {
            throw new BusinessException("没有找到采购合同。");
        }

        PurchaseOrderUpdateDto obj = new PurchaseOrderUpdateDto();
        obj.setSupplierEntId(requirementPlanExt.getProviderEntId());
        obj.setPlanDeliverDate(req.getPlanDeliver());
        obj.setContractCode(contractItemExt.get().getContractCode());
        obj.setPersonnelId(SecurityUtils.getUserContent().getPersonnelId());
        obj.setSubmit(true);

        PurchaseOrderItemDto objItem = new PurchaseOrderItemDto();
        objItem.setSkuId(req.getSkuId());
        objItem.setQty(req.getQty());
        List<PurchaseOrderItemDto> items = new ArrayList<>();
        items.add(objItem);

        obj.setItems(items);
        return add(obj);
    }

    @Override
    public PurchaseInventoryInReadyVo queryInventoryInReady(String purchaseOrderId) {
        PurchaseOrder order = baseMapper.selectById(purchaseOrderId);
        if (order == null) {
            throw new BusinessEntityNotFoundException(purchaseOrderId, "采购订单");
        }

        PurchaseInventoryInReadyVo note = new PurchaseInventoryInReadyVo();
        note.setPurchaseOrderCode(order.getCode());
        note.setPurchaseOrderId(purchaseOrderId);
        note.setSupplierName(order.getSupplierEntName());
        note.setItems(queryDeliverPlanByOrder(purchaseOrderId));
        return note;
    }

    @Override
    public String addByContract(String contractId) {
        ContractVo contract = contractService.queryViewById(contractId);
        if (contract == null) {
            throw new BusinessEntityNotFoundException(contractId, "合同");
        }
        if (contract.getType() != ContractTypeEnum.Purchase) {
            throw new BusinessException("指定的合同不是采购合同。");
        }
        if (!contract.getAuditStatus()) {
            throw new BusinessException("合同没有审核。");
        }
        if (contract.getIsDelete()) {
            throw new BusinessException("合同已作废，不能使用。");
        }

        PurchaseOrderAddDto obj = new PurchaseOrderAddDto();
        obj.setContractCode(contract.getCode());
        obj.setSupplierEntId(contract.getBusinessEntId());
        obj.setPersonnelId(SecurityUtils.getUserContent().getPersonnelId());

        List<PurchaseOrderItemDto> items = new ArrayList<>();
        for (ContractItemExt item : contract.getItems()) {
            PurchaseOrderItemDto objItem = new PurchaseOrderItemDto();
            objItem.setSkuId(item.getSkuId());
            objItem.setQty(item.getQty());
            items.add(objItem);
        }
        obj.setItems(items);
        return add(obj);
    }

    @Override
    public void addByService(String productionOrderId, String productionOrderItemId, String seqItemId) {
        ProductionOrderView order = productionOrderService.queryViewByOrderId(productionOrderId);
        if (order == null) {
            throw new BusinessEntityNotFoundException(productionOrderId, "生产订单");
        }
        if (!order.getSubmitStatus()) {
            throw new BusinessException("生产订单没有提交。");
        }

        // 查询工序绑定的物料
        ProductionSeqItem seqItem = productionSeqItemMapper.selectById(seqItemId);
        if (seqItem == null) {
            throw new BusinessEntityNotFoundException(seqItemId, "工序");
        }
        System.out.println("SeqName : " + seqItem.getName());
        System.out.println("Seq sku : " + seqItem.getRelationSkuId());

        //在供货协议中找到最便宜的那一笔
        Optional<ContractItemExt> contractItem = contractService.queryItemBySku(seqItem.getRelationSkuId(), -1, 1).getRecords().stream().filter(s -> s.getIsFrame()).sorted(Comparator.comparing(ContractItemExt::getPrice)).findFirst();
        if (!contractItem.isPresent()) {
            throw new BusinessException("工序委外所需采购的物料没有《年度价格协议》。");
        }
        if (!contractItem.get().getAuditStatus()) {
            throw new BusinessException("工序委外所需采购的物料对应的《年度价格协议》没有审核。");
        }

        //创建采购单头
        PurchaseOrderUpdateDto obj = new PurchaseOrderUpdateDto();
        obj.setSupplierEntId(contractItem.get().getBusinessEntId());
        obj.setContractCode(contractItem.get().getContractCode());
        obj.setOrderType(PurchaseOrderTypeEnum.Product_Requirement);
        obj.setPersonnelId(SecurityUtils.getUserContent().getPersonnelId());
        obj.setPlanDeliverDate(order.getPlanWorkDate());
        obj.setServices(true);
        obj.setSubmit(true);
        obj.setProductionOrderId(order.getOrderId());

        //创建采购明细
        List<PurchaseOrderItemDto> items = new ArrayList<>();
        PurchaseOrderItemDto objItem = new PurchaseOrderItemDto();
        objItem.setSkuId(seqItem.getRelationSkuId());
        objItem.setQty(order.getProductionQty() * seqItem.getRelationUserQty());
        objItem.setPrice(contractItem.get().getPrice());
        objItem.setProductionOrderItemId(productionOrderItemId);
        items.add(objItem);
        obj.setItems(items);

        String id = save(obj);
        System.out.println("purchase Order Id : " + id);
    }

    @Transactional
    @Override
    public void update(PurchaseOrderUpdateDto req) {
        save(req);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void save(List<PurchaseOrderUpdateDto> reqs) {
        for (PurchaseOrderUpdateDto req : reqs) {
            save(req);
        }
    }

    @Transactional
    @Override
    public void saveAndSubmit(List<PurchaseOrderUpdateDto> reqs) {
        for (PurchaseOrderUpdateDto req : reqs) {
            String id = save(req);
            submit(id);
        }
    }

    @Override
    public String save(PurchaseOrderUpdateDto req) {
//        System.out.println(req);
//        return null;

        if (StringUtils.isNullOrEmpty(req.getItems())) {
            throw new BusinessException("订单明细不能为空。");
        }

        PurchaseOrder obj = getById(req.getId());
        if (obj == null) {
            obj = new PurchaseOrder();
            obj.setCode(String.format("PO-%s%04d", DateUtils.formatDate(new Date(), "yyyyMM"), baseMapper.maxCode() + 1));
        } else {
            if (obj.getSubmitStatus()) {
                throw new BusinessException("订单已提交，不能修改。");
            }
        }
        if (StringUtils.isNullOrEmpty(req.getContractCode()) && StringUtils.isNullOrEmpty(req.getSupplierEntId())) {
            throw new BusinessException("采购合同号和供应商不能都为空。");
        }
        ContractVo contract;
        if (!StringUtils.isNullOrEmpty(req.getContractCode())) {
            contract = contractService.queryViewByCode(req.getContractCode());
            if (contract == null) {
                throw new BusinessEntityNotFoundException(req.getContractCode(), "合同号");
            }
        } else {
            contract = contractService.queryPurchaseFrame(req.getSupplierEntId());
            if (contract == null) {
                Ent ent = entService.queryById(req.getSupplierEntId());
                if (ent == null) {
                    throw new BusinessEntityNotFoundException(req.getSupplierEntId(), "供应商");
                }
                throw new BusinessException(String.format("供应商【%s】名下没有有效的采购合同。", ent.getName()));
            }
        }
        if (contract.getType() != ContractTypeEnum.Purchase) {
            throw new BusinessException("当前供应商的合同不是采购合同。");
        }
        if (!contract.getAuditStatus()) {
            throw new BusinessException("指定的合同【" + req.getContractCode() + "】没有审核。");
        }

        obj.setContractCode(contract.getCode());
        obj.setPlanDeliverDate(req.getPlanDeliverDate());

        Ent ent = entService.queryById(req.getSupplierEntId());
        if (ent == null) {
            throw new BusinessEntityNotFoundException(req.getSupplierEntId(), "供应商");
        }
        obj.setSupplierEntId(ent.getId());
        obj.setSupplierEntName(ent.getName());
        obj.setOrderType(req.getOrderType());
        obj.setIsServices(req.isServices());
        obj.setProductionOrderId(req.getProductionOrderId());

        if (req.isSubmit()) {
            obj.setSubmitAt(SecurityUtils.getUserContent().getId());
            obj.setSubmitAtName(SecurityUtils.getUserContent().getPersonnelName());
            obj.setSubmitTime(new Date());
            obj.setSubmitStatus(true);
        }

        if (StringUtils.isNullOrEmpty(req.getPersonnelId())) {
            obj.setPersonnelId(SecurityUtils.getUserContent().getPersonnelId());
            obj.setPersonnelName(SecurityUtils.getUserContent().getPersonnelName());
        } else {
            Personnel personnel = personnelService.queryById(req.getPersonnelId());
            if (personnel != null) {
                obj.setPersonnelId(personnel.getId());
                obj.setPersonnelName(personnel.getName());
            } else {
                throw new BusinessException("指定的经办人无效。");
            }
        }
        obj.insertOrUpdate();

        // 清除订单明细
        LambdaQueryWrapper<PurchaseOrderItem> lq = Wrappers.lambdaQuery();
        lq.eq(PurchaseOrderItem::getOrderId, obj.getId());
        purchaseOrderItemMapper.delete(lq);

        if (!StringUtils.isNullOrEmpty(req.getItems())) {
            for (PurchaseOrderItemDto item : req.getItems()) {

                if (item.getQty() == 0) {
                    continue;
                }

                Optional<ContractItemExt> contractItem = contract.getItems().stream().filter(s -> s.getIsFrame() && s.getIsDelete() == 0 && s.getSkuId().equals(item.getSkuId())).sorted(Comparator.comparing(ContractItemExt::getPrice)).findFirst();
                if (!contractItem.isPresent()) {
                    ProductSkuExt sku = productSkuService.queryViewById(item.getSkuId());
                    if (sku != null) {
                        throw new BusinessException(String.format("所采购的物料【%s，%s】不在供应商【%s】的供货范围中。", sku.getSkuCode(), sku.getName(), contract.getBusinessEntName()));
                    } else {
                        throw new BusinessException(String.format("所采购的物料【%s】不在供应商【%s】的供货范围中。", item.getSkuId(), contract.getBusinessEntName()));
                    }
                }
                if (contractItem.get().getPrice() == 0) {
                    throw new BusinessException("合同价格不能小于0。");
                }

                PurchaseOrderItem objItem = new PurchaseOrderItem();
                objItem.setId(item.getId());
                objItem.setSkuId(item.getSkuId());
                objItem.setOrderId(obj.getId());
                objItem.setQty(item.getQty());
                objItem.setPrice(contractItem.get().getPrice());
                objItem.setProductionOrderItemId(item.getProductionOrderItemId());
                objItem.insertOrUpdate();
            }
        }
        return obj.getId();
    }

    @Override
    public void delete(String id) {
        getBaseMapper().deleteById(id);
    }

    @Override
    public void submit(String id) {
        PurchaseOrder obj = getById(id);
        if (obj == null) {
            throw new BusinessEntityNotFoundException(id, "采购订单");
        }
        if (obj.getSubmitStatus()) {
            throw new BusinessException("采购订单不能重复提交。");
        }

        obj.setSubmitAt(SecurityUtils.getUserContent().getId());
        obj.setSubmitAtName(SecurityUtils.getUserContent().getPersonnelName());
        obj.setSubmitTime(new Date());
        obj.setSubmitStatus(true);
        obj.updateById();
    }

    @Override
    public void submitCancel(String id) {
        PurchaseOrder order = baseMapper.selectById(id);
        if (order == null) {
            throw new BusinessEntityNotFoundException(id, "采购订单");
        }
        if (!order.getSubmitStatus()) {
            throw new BusinessException("采购订单未提交。");
        }
        if (order.getIsDelete()) {
            throw new BusinessException("采购订单已删除，不能执行此操作。");
        }
        if (queryItemById(id, -1, 1).getRecords().stream().mapToDouble(s -> s.getDeliverQty()).sum() > 0) {
            throw new BusinessException("采购订单已开始收货，不能撤销。");
        }
        List<InventoryNoteItemExt> list = inventoryNoteService.queryItemExtByRelationNoteId(id);
        if (!StringUtils.isNullOrEmpty(list)) {
            if (list.stream().filter(s -> s.getSubmitStatus() && s.getIsDelete() == false).count() > 0) {
                throw new BusinessException("采购订单存在有效的收货入库，不能撤销。");
            }
        }

        order.setSubmitStatus(false);
        order.setSubmitTime(null);
        order.setSubmitAtName(null);
        order.updateById();
    }

    @Override
    public List<PurchaseMonthSumExt> queryMonthSum(int year, int month) {
        LambdaQueryWrapper<PurchaseMonthSumExt> lq = Wrappers.lambdaQuery();
        lq.eq(PurchaseMonthSumExt::getAccountYear,year);
        lq.eq(PurchaseMonthSumExt::getAccountMonth,month);
        return purchaseMonthSumExtMapper.selectList(lq);
    }

    @Override
    public PurchaseOrder queryById(String id) {
        return getBaseMapper().selectById(id);
    }

    @Override
    public IPage<PurchaseOrderItemExt> queryItemView(PurchaseOrderItemQueryDto req) {
        Page<PurchaseOrderItemExt> page = new Page(req.getPageIndex(), req.getPageSize());
        LambdaQueryWrapper<PurchaseOrderItemExt> lq = Wrappers.lambdaQuery();
        lq.eq(PurchaseOrderItemExt::getSubmitStatus, true);
        if (!StringUtils.isNullOrEmpty(req.getOrderCode())) {
            lq.eq(PurchaseOrderItemExt::getCode, req.getOrderCode());
        }
        if (!StringUtils.isNullOrEmpty(req.getContractCode())) {
            lq.eq(PurchaseOrderItemExt::getContractCode, req.getContractCode());
        }
        if (!StringUtils.isNullOrEmpty(req.getEntName())) {
            lq.like(PurchaseOrderItemExt::getSupplierEntName, req.getEntName());
        }
        if (!StringUtils.isNullOrEmpty(req.getSkuCode())) {
            lq.eq(PurchaseOrderItemExt::getSkuCode, req.getSkuCode());
        }
        if (req.getStartDate() != null) {
            lq.ge(PurchaseOrderItemExt::getSubmitTime, req.getStartDate());
        }
        if (req.getEndDate() != null) {
            lq.le(PurchaseOrderItemExt::getSubmitTime, req.getEndDate());
        }
        if(!StringUtils.isNullOrEmpty(req.getProductionOrderCode())){
            lq.eq(PurchaseOrderItemExt::getProductionOrderCode,req.getProductionOrderCode());
        }
        lq.orderByDesc(PurchaseOrderItemExt::getCode).orderByAsc(PurchaseOrderItemExt::getSkuCode);
        return purchaseOrderItemExtMapper.selectPage(page, lq);
    }

    @Override
    public PurchaseOrderVo queryViewById(String id) {
        PurchaseOrderExt obj = purchaseOrderExtMapper.selectById(id);
        if (obj == null) {
            return null;
        }

        PurchaseOrderVo ret = new PurchaseOrderVo();
        BeanUtils.copyProperties(obj, ret);

        LambdaQueryWrapper<PurchaseOrderItemExt> lq = Wrappers.lambdaQuery();
        lq.eq(PurchaseOrderItemExt::getOrderId, id);
        ret.setItems(purchaseOrderItemExtMapper.selectList(lq));
        return ret;
    }

    @Override
    public IPage<PurchaseOrderExt> query(String searchText, Integer pageSize, Integer pageIndex) {
        IPage<PurchaseOrderExt> page = new Page<>(pageIndex, pageSize);
        LambdaQueryWrapper<PurchaseOrderExt> lq = Wrappers.lambdaQuery();
        lq.eq(PurchaseOrderExt::getIsDelete, false);
        if (!StringUtils.isNullOrEmpty(searchText)) {
            lq.like(PurchaseOrderExt::getCode, searchText)
                    .or().like(PurchaseOrderExt::getContractCode, searchText)
                    .or().like(PurchaseOrderExt::getSupplierEntName, searchText)
                    .or().like(PurchaseOrderExt::getPersonnelName, searchText);
        }
        lq.eq(PurchaseOrderExt::getIsDelete, false);
        lq.orderByDesc(PurchaseOrderExt::getCreateTime);
        return purchaseOrderExtMapper.selectPage(page, lq);
    }

    @Override
    public IPage<PurchaseOrderItemExt> queryItemById(String id, Integer pageSize, Integer pageIndex) {
        Page<PurchaseOrderItemExt> page = new Page(pageIndex, pageSize);
        LambdaQueryWrapper<PurchaseOrderItemExt> lq = Wrappers.lambdaQuery();
        lq.eq(PurchaseOrderItemExt::getOrderId, id);
        return purchaseOrderItemExtMapper.selectPage(page, lq);
    }

    @Override
    public List<PurchaseOrder> queryByProductionOrder(String id) {
        LambdaQueryWrapper<PurchaseOrder> lq = Wrappers.lambdaQuery();
        lq.eq(PurchaseOrder::getProductionOrderId, id);
        return baseMapper.selectList(lq);
    }

    @Override
    public PurchaseOrderItemExt queryItemByProductionItem(String id) {
        LambdaQueryWrapper<PurchaseOrderItemExt> lq = Wrappers.lambdaQuery();
        lq.eq(PurchaseOrderItemExt::getProductionOrderItemId, id);
        lq.eq(PurchaseOrderItemExt::getIsDelete, false);
        return purchaseOrderItemExtMapper.selectOne(lq);
    }

    @Override
    public List<PurchaseOrderItemExt> queryItemByProductionOrder(String productionOrderId) {
        LambdaQueryWrapper<PurchaseOrderItemExt> lq = Wrappers.lambdaQuery();
        lq.eq(PurchaseOrderItemExt::getProductionOrderId,productionOrderId);
        lq.eq(PurchaseOrderItemExt::getSubmitStatus,true);
        lq.eq(PurchaseOrderItemExt::getIsDelete,false);
        return purchaseOrderItemExtMapper.selectList(lq);
    }

    @Override
    public IPage<PurchaseOrderDeliverPlanExt> queryDeliverPlan(String searchText, Integer pageSize, Integer pageIndex) {
        IPage<PurchaseOrderDeliverPlanExt> page = new Page<>(pageIndex, pageSize);
        LambdaQueryWrapper<PurchaseOrderDeliverPlanExt> lq = Wrappers.lambdaQuery();
        lq.gt(PurchaseOrderDeliverPlanExt::getDeliverDiffCount, 0);
        if (!StringUtils.isNullOrEmpty(searchText)) {
            lq.like(PurchaseOrderDeliverPlanExt::getSkuCode, searchText).or().
                    like(PurchaseOrderDeliverPlanExt::getSkuName, searchText).
                    or().eq(PurchaseOrderDeliverPlanExt::getOrderCode,searchText).or().like(PurchaseOrderDeliverPlanExt::getSupplierEntName,searchText);
        }
        lq.orderByAsc(PurchaseOrderDeliverPlanExt::getSkuCode);
        return purchaseOrderDeliverPlanExt.selectPage(page, lq);
    }

    @Override
    public List<PurchaseOrderDeliverPlanExt> queryDeliverPlanByOrder(String purchaseOrderId) {
        LambdaQueryWrapper<PurchaseOrderDeliverPlanExt> lq = Wrappers.lambdaQuery();
        lq.eq(PurchaseOrderDeliverPlanExt::getOrderId, purchaseOrderId);
        lq.ne(PurchaseOrderDeliverPlanExt::getDeliverDiffCount, 0);
        lq.orderByAsc(PurchaseOrderDeliverPlanExt::getSkuCode);
        return purchaseOrderDeliverPlanExt.selectList(lq);
    }

    @Override
    public IPage<PurchaseSummaryExt> querySummary(String searchText, Integer pageSize, Integer pageIndex) {
        IPage<PurchaseSummaryExt> page = new Page<>(pageIndex, pageSize);
        LambdaQueryWrapper<PurchaseSummaryExt> lq = Wrappers.lambdaQuery();
        if (!StringUtils.isNullOrEmpty(searchText)) {
            lq.like(PurchaseSummaryExt::getSupplierEntName, searchText);
        }
        lq.orderByDesc(PurchaseSummaryExt::getOrderMoney);
        return purchaseSummaryExtMapper.selectPage(page, lq);
    }

    @Override
    public IPage<PurchaseSummaryItemExt> querySummaryItem(String id, int pageSize, int pageIndex) {
        IPage<PurchaseSummaryItemExt> page = new Page<>(pageIndex, pageSize);
        LambdaQueryWrapper<PurchaseSummaryItemExt> lq = Wrappers.lambdaQuery();
        lq.eq(PurchaseSummaryItemExt::getSupplierEntId, id);
        lq.orderByAsc(PurchaseSummaryItemExt::getSkuCode);
        return purchaseSummaryItemExtMapper.selectPage(page, lq);
    }

    @Override
    public IPage<PurchaseOrderItemExt> queryItemBySupplier(String id, int pageSize, int pageIndex) {
        IPage<PurchaseOrderItemExt> page = new Page<>(pageIndex, pageSize);
        LambdaQueryWrapper<PurchaseOrderItemExt> lq = Wrappers.lambdaQuery();
        lq.eq(PurchaseOrderItemExt::getSupplierEntId, id);
        lq.orderByDesc(PurchaseOrderItemExt::getCode);
        return purchaseOrderItemExtMapper.selectPage(page, lq);
    }

    @Override
    public IPage<PurchaseInNoteToFinance> queryPurchaseInNote(String searchText, int year, int month, int pageSize, int pageIndex) {
        IPage<PurchaseInNoteToFinance> page = new Page<>(pageIndex, pageSize);
        LambdaQueryWrapper<PurchaseInNoteToFinance> lq = Wrappers.lambdaQuery();
        if (!StringUtils.isNullOrEmpty(searchText)) {
            lq.like(PurchaseInNoteToFinance::getNoteCode, searchText)
                    .or().like(PurchaseInNoteToFinance::getOrderCode, searchText)
                    .or().like(PurchaseInNoteToFinance::getContractCode, searchText)
                    .or().like(PurchaseInNoteToFinance::getSupplierEntCode, searchText)
                    .or().like(PurchaseInNoteToFinance::getSupplierEntName, searchText);
        }
        lq.eq(PurchaseInNoteToFinance::getAccountYear, year);
        lq.eq(PurchaseInNoteToFinance::getAccountMonth, month);
        lq.orderByAsc(PurchaseInNoteToFinance::getAuditTime);
        return purchaseInNoteToFinanceMapper.selectPage(page, lq);
    }

    @Override
    public IPage<PurchaseInNoteExt> queryPurchaseInNoteBySupplier(String entId, int pageSize, int pageIndex) {
        IPage<PurchaseInNoteExt> page = new Page<>(pageIndex, pageSize);
        LambdaQueryWrapper<PurchaseInNoteExt> lq = Wrappers.lambdaQuery();
        lq.eq(PurchaseInNoteExt::getSupplierEntId, entId);
        lq.eq(PurchaseInNoteExt::getAuditStatus,true);
        lq.eq(PurchaseInNoteExt::getSubmitStatus,true);
        lq.isNull(PurchaseInNoteExt::getInvoiceNoteId);
        lq.orderByAsc(PurchaseInNoteExt::getAccountDate);
        return purchaseInNoteExtMapper.selectPage(page, lq);
    }

    @Override
    public IPage<PurchaseOrderExt> queryNotContractOrder(String entId, int pageSize, int pageIndex) {
        IPage<PurchaseOrderExt> page = new Page<>(pageIndex, pageSize);
        LambdaQueryWrapper<PurchaseOrderExt> lq = Wrappers.lambdaQuery();
        lq.eq(PurchaseOrderExt::getIsDelete,false);
        lq.eq(PurchaseOrderExt::getSupplierEntId, entId).eq(PurchaseOrderExt::getIsDelete, false).eq(PurchaseOrderExt::getSubmitStatus, true).
                and(s -> s.eq(PurchaseOrderExt::getIsFrame, true).or().isNull(PurchaseOrderExt::getContractCode));
        lq.orderByAsc(PurchaseOrderExt::getCode);
        return purchaseOrderExtMapper.selectPage(page, lq);
    }
}